const gulp = require('gulp');
// gulp core function
const { src, dest, series, parallel, watch } = require('gulp');
// Refresh the browser in real time
const browserSync = require('browser-sync').create();
const reload = browserSync.reload;

const nodemon = require('gulp-nodemon');
const through2 = require('through2');
// const gulpBabel = require('gulp-babel');
// Distinguish development and production environments
const production = process.env.NODE_ENV === 'production' ? true : false;
const paths = {
    staticRoot: ['public'],
    staticView: ['views']
}

// Refresh browser
function reloadBrowser(done) {
    reload();
    done();
}

// Monitoring static file changes
function watcher(done) {
    // watch static
    watch(paths.staticView,{ delay: 500 }, series(reloadBrowser));
    console.log('watch!');
    done();
}


// var proxyMiddleware = require('http-proxy-middleware');
// Static server
function serve(done) {
    console.log(process.env.DEBUG === 'false');
    nodemon({
        script: './bin/www',
        ignore: ['.vscode', '.idea', 'node_modules'],
        env: {
            'NODE_ENV': 'development'
        //,'REMOTE_API': config.remoteApi
        },
        stdout: false
    }).on('restart', function(){
        console.log('nodemon restart is ok ......');
        //setTimeout(reload, process.env.DEBUG === 'false' ? 0 : 1000);
    }).on('start',function(){
        console.log('nodemon start is ok ......');
        browserSync.init({
            // server: {
            //     baseDir: paths.staticRoot
            //     ,middleware: [proxyMiddleware.createProxyMiddleware('/', {target:'http://localhost:3000'})]
            //     //middleware: [apiProxy],//proxy
            // },
            browser: "chrome",//"firefox", or delete, open default browser
            proxy:'http://localhost:3000',
            //files:['./public/**','./routes/**','./views/**'], 
            port:  8090,      
            //reloadDelay: 0,      
            ghostMode: false, //默认true，滚动和表单在任何设备上输入将被镜像到所有设备里，会影响本地的协同编辑消息，故关闭
        }, function(){})
    }).on('readable', function(){
        console.log('readable restart is ok ......');
        this.stdout.pipe(through2(function(chunk, enc, callback) {
            if(chunk.toString().substr(0,18) == 'nodemon has ended!'){                
                console.log('chunkend:' + chunk.toString());
                setTimeout(reload, 0);
            }        
            callback();
          })).pipe(process.stdout);
        this.stderr.pipe(process.stderr);        
    });
    done();
}

exports.default = series(watcher, serve);